package com.spark.actions.sys;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;

import com.spark.core.Message;
import com.spark.core.SparkContext;
import com.spark.dao.SessionFactory;

public class ScreenAction extends DefaultAction {
	
	public static final String FIELD_SCREEN_CODE = "SCREEN_CODE";
	public static final String FIELD_SCREEN_PATH = "SCREEN_PATH";
	
	/**
	 * 创建页面.
	 * @param context
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public void createScreen(SparkContext context) throws Exception {
		doExecute(context, "sys_screens.insert", ACTION_INSERT);
	}
	
	/**
	 * 更新页面.
	 * @param context
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public void updateScreen(SparkContext context) throws Exception {
		doExecute(context, "sys_screens.update", ACTION_UPDATE);
	}
	
	@SuppressWarnings("unchecked")
	private boolean validateScreen(Map map, Message message){
		return isNotEmpty(map.get(FIELD_SCREEN_CODE), message,"功能代码不能为空!")||isNotEmpty(map.get(FIELD_SCREEN_PATH), message,"页面路径不能为空!");
	}
	
	@SuppressWarnings("unchecked")
	protected void doExecute(SparkContext context, String statement, String action) throws Exception{
		Map requestData = getRequestData(context);
		List list = (List)requestData.get(PARAMETER);
		Message message = new Message(true);
		if(list!=null && list.size() > 0){
			Map map = (Map)list.get(0);
			if(validateScreen(map,message)){
				SqlSession sqlSession = SessionFactory.getSession();
				try {
					Integer count = (Integer)sqlSession.selectOne("sys_screens.selectDuplicateScreen",map);
					if(count>0){
						message.setWarning("存在相同路径的页面!");
						message.setWidth(300);
						message.setHeiht(150);
					}else{
						doAction(sqlSession, action, statement,map);
					}
				} finally {
					SessionFactory.closeSession(sqlSession);
				}
			}
		}
		writeMessage(context, message);
	}

	
	
}
